package com.gotop.mapper.core.log.util;

import com.gotop.common.config.server.ServerInfo;
import com.gotop.common.utils.DateUtil;
import com.gotop.common.utils.WebUtil;
import com.gotop.common.utils.auth.SecureUtil;
import com.gotop.model.LogAbstract;
import org.apache.commons.lang3.ObjectUtils;

import javax.servlet.http.HttpServletRequest;
import java.net.URI;
import java.net.URISyntaxException;

/**
 * @program: cem
 * @description:
 * @author: superfish
 * @create: 2020-12-28 14:09
 **/
public class LogAbstractUtil {
    public LogAbstractUtil() {
    }

    public static void addRequestInfoToLog(HttpServletRequest request, LogAbstract logAbstract) {
        if (ObjectUtils.isNotEmpty(request)) {
            logAbstract.setRemoteIp(WebUtil.getIP(request));
            logAbstract.setUserAgent(request.getHeader("user-agent"));
            logAbstract.setRequestUri(getPath(request.getRequestURI()));
            logAbstract.setMethod(request.getMethod());
            logAbstract.setParams(WebUtil.getRequestParamString(request));
            logAbstract.setCreateBy(SecureUtil.getUserAccount(request));
        }

    }

    public static void addOtherInfoToLog(LogAbstract logAbstract, ServerInfo serverInfo) {
//        logAbstract.setServiceId(bladeProperties.getName());
        logAbstract.setServerHost(serverInfo.getHostName());
        logAbstract.setServerIp(serverInfo.getIpWithPort());
//        logAbstract.setEnv(bladeProperties.getEnv());
        logAbstract.setCreateTime(DateUtil.now());
        if (logAbstract.getParams() == null) {
            logAbstract.setParams("");
        }

    }

    public static String getPath(String uriStr) {
        URI uri;
        try {
            uri = new URI(uriStr);
        } catch (URISyntaxException var3) {
            throw new RuntimeException(var3);
        }

        return uri.getPath();
    }
}
